<?php
function xAPProcessIncoming($msg,$cIP,$cPort){
	//tidy message
	$msg=trim($msg);
	$msg=str_replace("\r","\n",$msg);
	$msg=str_replace("\n\n","\n",$msg);

	$armsg=explode("\n",$msg);
	//process
	switch($armsg[0]){
		case "xap-hbeat":
			xAPProcessHeartBeat($armsg);
			break;
		case "xap-header":
			xAPProcessMessage($armsg);
			break;
	}
}
function xAPProcessMessage($armsg){
global $config;
	// fired on the recipt of a xAP message
	$msg=xAPProcessMessageToArray($armsg);

	dbtransactionstart();

	foreach($config["xAPInc"] as $value){

		if(strtolower($msg["header"]["class"])==$value["class"] || $value["class"]=="all"){
			xAPLog("xAP","Calling ".$value["function"],"");
			$value["function"]($msg);
		}
	}

	dbtransactionend();
}

function xAPProcessHeartBeat($armsg){
	// fired on the receipt of a xAP Heartbeat
	$msg=xAPProcessMessageToArray($armsg);
	//print_r($header);
}



function xAPProcessMessageToArray($armsg){
	// build an array of the message elements
$isheader=1;
$isbody=0;
	for ($i=0;$i<count($armsg);$i++){

		if($isbody==1 && $isheader==2){
			if ($armsg[$i]=="}"){ break;} //exit if header ended
			if (strpos($armsg[$i],"=")>0){
				$line=explode("=",$armsg[$i]); //  split before and after the =
				$msg["body"][$sectionname][strtolower($line[0])]=$line[1];
			}
		}
		if($isheader==1){
			if ($armsg[$i]=="}"){ $isheader=2;$isbody=1;} //move on to body
			if (strpos($armsg[$i],"=")>0){
				$line=explode("=",$armsg[$i]); //  split before and after the =
				$msg["header"][strtolower($line[0])]=$line[1];
			}
		}
		if ($armsg[$i]=="{"){ $sectionname=strtolower($armsg[$i-1]);} // store teh section name
	}
	
	return $msg;
}

?>